import Qs from 'qs'
import cacheAdapter from './axios-cache-adapter'
import LRUCache from 'lru-cache'

const cacheCfg = new LRUCache({
  maxAge: process.env.cacheTime,
  max: process.env.cacheMax
})

export default function ({ $axios, $cookies, redirect, error: nuxtError }) {
  $axios.defaults.adapter = cacheAdapter($axios.defaults.adapter, {
    enabledByDefault: process.env.cache || false,
    defaultCache: cacheCfg,
    cacheFlag: 'cache'
  })

  $axios.onRequest(config => {
    if(process.env.baseUrl){
      config.baseURL = process.env.baseUrl
    }
    if (config.method === 'post') {
      $axios.defaults.transformRequest = [function (data) {
        data = Qs.stringify(data)
        return data
      }]
    }
    const token = $cookies.get('token') || ''
    $axios.setToken(token, 'Bearer')
    const _params = config.params || config.data
    if (process.env.debug) {
      console.log('Making request to %s, the params is %s, the token is %s.',
      config.baseURL + config.url, JSON.stringify(_params), token)
    }
  })

  $axios.onResponse(response => {
    const { status, statusText, data } = response
    if (process.env.debug) {
      console.log('Response is done. the code is %s, the message is %s.', status, statusText)
      console.log('The response data is: %s. ', JSON.stringify(data))
    }
    return data
  })

  $axios.onError(error => {
    const code = parseInt(error.response && error.response.status)
    if (code === 400) {
      redirect('/400')
    } else if(code === 500){
      redirect('/sorry')
    } else{
      nuxtError({
        statusCode: error.response.status,
        message: error.message
      })
      return Promise.resolve(false)
    }
  })
}